﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Uranus.WeiStationAPI.Common
{
    public class RequestDecrypt
    {
        private static ICryptoTransform cTransform = null;
        public static string Decrypt(string toDecrypt)
        {
            if (cTransform == null)
            {
                byte[] keyArray = get_key();
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                cTransform = rDel.CreateDecryptor();
            }
            byte[] toEncryptArray = HexToByte(toDecrypt);

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        private static byte[] get_key()
        {
            string key = CommonModel.RequestDecryptKey;
            byte[] result = Encoding.UTF8.GetBytes(key);
            MD5 md5 = new MD5CryptoServiceProvider();
            return md5.ComputeHash(result);
        }

        private static byte[] HexToByte(string msg)
        {
            byte[] comBuffer = new byte[msg.Length / 2];
            for (int i = 0; i < msg.Length; i += 2)
            {
                comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
            }
            return comBuffer;
        }
    }
}